# -*- coding: utf-8 -*-
# @Time : 2022/5/29 22:17
# @Author : Dftre
# @Email : 3066417822@qq.com
# @File : mysql.py
# @Project : 代码生成器
# @Version : 1.0.5
import pymysql as pymysql

class MysqlTableMessage:
    def __init__(self, user, password, database, table, host="localhost", port=3306, charset='utf8'):
        self.database = database
        try:
            self.conn = pymysql.connect(
                user=user, password=password, database=database,
                host=host, port=port, charset=charset
            )
        except:
            raise Exception("链接数据库出现错误")
        self.cursor = self.conn.cursor(cursor=pymysql.cursors.DictCursor)
        self.sql = 'select COLUMN_NAME,COLUMN_COMMENT, DATA_TYPE ' \
                   'from INFORMATION_SCHEMA.Columns where table_name=%s and table_schema=%s'
        try:
            self.cursor.executemany(self.sql, [(table, self.database)])
        except:
            raise Exception("sql语句错误，请联系开发者")
        data = self.cursor.fetchall()
        self.fields = [{'name': i['COLUMN_NAME'], 'type': i['DATA_TYPE'], 'label': i['COLUMN_COMMENT']} for i in data]

    def sub(self, template: str, bracket=('{', '}'), ever_bracket=('', ''), no=None):
        if no is None:
            no = []
        out = [bracket[0]]
        for i in self.fields:
            if i['name'] not in no:
                out.append(ever_bracket[0] +
                           template.format(i['name'], i['label'], i['type']) +
                           ever_bracket[1])
        out.append(bracket[1])
        return '\n'.join(out)


if __name__ == '__main__':
    MTM = MysqlTableMessage(
        user="root",
        password="123456",
        database="xgk2023",
        table='users'
    )
    print(MTM.sub("'{0}':({1},{2})", no=['role', 'root']))
    pass
